package com.cloudkinto.service.region.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.JpRegionDao;
import com.cloudkinto.entity.JpRegionDo;
import com.cloudkinto.entity.OrderOutputDo;
import com.cloudkinto.service.region.JpRegionService;
import com.cloudkinto.service.region.vo.JpRegionListRes;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author 张永远
 * @since 2020-06-08
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class JpRegionServiceImpl extends ServiceImpl<JpRegionDao, JpRegionDo> implements JpRegionService {
    @Autowired
    private JpRegionDao dao;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }


    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(JpRegionDo entityDo, Long userId) {
//        entityDo.setCreateBy(userId);
//        entityDo.setCreateTime(new Date());
//        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(JpRegionDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*JpRegionDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(JpRegionDo entityDo, Long userId) {
//        entityDo.setUpdateBy(userId);
//        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(JpRegionDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        JpRegionDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(JpRegionDo entityDo, Long userId) {
//        entityDo.setDeleteBy(userId);
//        entityDo.setDeleteTime(new Date());
    }

    @Override
    public Object detail(Long id) {
        JpRegionDo entityDo = dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<JpRegionListRes> getList(Map<String, String> map) {
        QueryWrapper<JpRegionDo> wrapper = queryBuild(map);
        List<JpRegionDo> list = this.list(wrapper);
        List<JpRegionListRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<JpRegionDo> wrapper = queryBuild(map);
        IPage<JpRegionDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<JpRegionListRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<JpRegionListRes> handlerListAfter(List<JpRegionDo> list) {
        List<JpRegionListRes> result = new ArrayList<>();
        for (JpRegionDo jpRegionDo :
                list) {
            result.add(new JpRegionListRes(jpRegionDo.getId(), jpRegionDo.getName()));
        }
        return result;
    }

    private IPage<JpRegionDo> pageInit(Map<String, String> map) {
        IPage<JpRegionDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<JpRegionDo> queryBuild(Map<String, String> map) {
        QueryWrapper<JpRegionDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("keyword", map.get("keyword"));
        }
        return wrapper;
    }

    /**
     * 通过postCode 获取地区id
     *
     * @param code
     * @return
     */
    @Override
    public Long getStateIdByPostCode(String code) {
        Long stateId = 0L;
        //得到所属县
        JpRegionDo regionDo = getRegionDoByPostCode(code);
        if (regionDo != null)
            stateId = regionDo.getJpStateId();
        return stateId;
    }

    /**
     * 通过postCode 获取县
     *
     * @param code
     * @return
     */
    @Override
    public JpRegionDo getRegionDoByPostCode(String code) {
        QueryWrapper wrapper = new QueryWrapper();
        String post2 = "";
        int postcode = 0;
        if (StringUtils.isBlank(code)) return null;
        String regEx = "[^0-9||^０-９]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(code);
        post2 = m.replaceAll("").trim();
        if (post2.length() > 7)
            post2 = post2.substring(0, 7);
        if (StringUtils.isBlank(post2)) return null;
        postcode = Integer.parseInt(post2);
        if (postcode < 100000) {//北海道特殊地区
            postcode = 400001;
        }
        wrapper.le("post_code_start", postcode);
        wrapper.ge("post_code_end", postcode);
        JpRegionDo regionDo = baseMapper.selectOne(wrapper);
        return regionDo;
    }

    @Override
    public JpRegionDo getRegionDoByPostCode(String code, List<JpRegionDo> regionDoList) {
        String post2 = "";
        int postcode = 0;
        if (StringUtils.isBlank(code)) return null;
        String regEx = "[^0-9||^０-９]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(code);
        post2 = m.replaceAll("").trim();
        if (post2.length() > 7)
            post2 = post2.substring(0, 7);
        if (StringUtils.isBlank(post2)) return null;
        postcode = Integer.parseInt(post2);
        if (postcode < 100000) {//北海道特殊地区
            postcode = 400001;
        }
        for (JpRegionDo jpRegionDo : regionDoList) {
            if (jpRegionDo.getPostCodeStart()<=postcode && jpRegionDo.getPostCodeEnd()>=postcode){
                return jpRegionDo;
            }
        }
        return null;
    }

    @Override
    public Long getStateIdByRegionId(Long fbaStorageRegion) {
        JpRegionDo regionDo = baseMapper.selectById(fbaStorageRegion);
        if (regionDo != null)
            return regionDo.getJpStateId();
        else
            return 0L;
    }

    public List<Long> getStopRegionId() {
        List<JpRegionDo> list = dao.selectList(new LambdaQueryWrapper<JpRegionDo>()
                .ne(JpRegionDo::getStopFlag, 0));
        return list.stream().map(JpRegionDo::getId).collect(Collectors.toList());
    }

    @Override
    public boolean jugStopRegion(OrderOutputDo et) {
        List<Long> collect = this.getStopRegionId();
        JpRegionDo jpRegionDo = this.getRegionDoByPostCode(et.getPostCode());
        if (jpRegionDo == null) {
            return false;
        }
        return collect.contains(jpRegionDo.getId());
    }

}
